﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace memcached.Tx
{
    /// <summary>
    /// We assume null is not a valid value.
    /// We assume the expiry information provided is also valid for Rollback operations.
    /// </summary>
    internal sealed class AddOp : SetOp
    {
        [System.Diagnostics.DebuggerHidden]
        public AddOp(ICache real, ICache temp, string key, object value, DateTime expireAt)
            : base(real, temp, key, value)
        {
            ExpireAt = expireAt;
        }

        [System.Diagnostics.DebuggerHidden]
        public AddOp(ICache real, ICache temp, string key, object value, int validFor)
            : base(real, temp, key, value)
        {
            ValidFor = validFor;
        }

        private readonly DateTime ExpireAt;
        private readonly int ValidFor;

        public override string Name
        {
            [System.Diagnostics.DebuggerHidden]
            get { return "Add:" + Key; }
        }

        public override object Execute()
        {
            if (ValidFor > 0)
                return Temp.Add(Key, ValidFor, Value);
            return Temp.Add(Key, ExpireAt, Value);
        }

        public override bool Persist()
        {
            bool res;
            if (ValidFor > 0)
                res = Store.Add(Key, ValidFor, Value);
            else
                res = Store.Add(Key, ExpireAt, Value);
            // true -> item added, remove on rollback
            // false-> item already exists, so no action in rollback
            Done = res;
            return true;
        }

        public override bool Rollback()
        {
            if (Done)
                return Store.Remove(Key);// item was added, so remove it now
            return true;
        }
    }
}